<?php

class AttrClassModel extends Model{
	public $table="attr_class";//如果不定义tablename  K方法，实例化表将不知道操作哪张表
	public $validate; //验证字段
	public function __init(){
		$this->validate=array(
			array('attr_name','nonull','属性名不能为空',2,1),
			array('show_type','nonull','显示类型不能为空',2,1)
			);
	}


	public function showAttr($id){
		$attrData = M('attr_class')->where(array('gt_id'=>$id))->all();
		if($attrData){
			return $attrData;
		}else{
			$this->error='还没有添加属性';
			return false;
		}
	}

	public function addAttr(){
		$this->validate=array(
			array('attr_name','nonull','属性名不能为空',2,1),
			array('show_type','nonull','显示类型不能为空',2,1)
			);
		$db = M('attr_class');
		if($db->where(array('attr_name'=>Q('attr_name'),'gt_id'=>Q('gt_id')))->find()){
			$this->error="属性名不能重复";
			return false;
		}
		
		if($this->create()){
			$ac_id = $this->add();
			if($ac_id){
				$show_type = Q('show_type');
				$this->addAttrValue($ac_id,$_POST['attr_value']);
				return true;
			}else{
				$this->error='属性值添加失败';
				return false;
			}

		}else{
			return false;
		}

	}
	

	public function saveAttr($ac_id){
		if($this->create()){
			if($this->where(array('ac_id'=>$ac_id))->save()){
				return true;
			}else{
				$this->error='商品属性表更新失败';
				return false;
			}
		}
	}

	public function saveAttrValue($ac_id){
		$attrValueModel = M('attr_value');
		$data = $attrValueModel->where(array('ac_id'=>$ac_id))->all();
		foreach ($data as $key => $value) {
			
		}
	}
	
	//添加属性值
	public function addAttrValue($ac_id,$attrValueData){
		$db = M('attr_value');
		$arr = array();
		if(!is_array($attrValueData)){
			$arr[] = $attrValueData;
		}else{
			$arr = $attrValueData;
		}
		foreach ($arr as $key => $data) {
			if(empty($data))continue;
			$insertData = array(
				'ac_id'=>$ac_id,
				'attr_value'=>$data
				);
			$db->add($insertData);
		}
		return true;
	}
	

	public function showFieldTpl(){
		$show_type = Q('show_type');
		$tpl = APP_PATH.'Field/'.$show_type.'/add.php';
		$content = $this->fetch($tpl);
		echo $content;exit;
	}
//删除属性表及属性值
	public function delAttr($ac_id){
		if($ac_id){
			$model = M('attr_value');
			if($model->delete('ac_id='.$ac_id)!==false){
				if(M('attr_class')->delete('ac_id='.$ac_id)!==false){
					return true;
				}else{
					$this->error='属性表删除失败';
					return false;
				}
			}else{
				$this->error='属性值表删除失败';
				return false;
			}
		}else{
			$this->error='参数不正确,缺少ac_id值';
			return false;
		}
	}

//删除属性值
	public function delAttrValue($ac_id){
		$model = M('attr_value');
		if($model->delete('ac_id='.$ac_id)!==false){
			return true;
		}else{
			$this->error='属性值表删除失败';
			return false;
		}
	}
}

?>
